package com.th.campusmatchbackend.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.th.campusmatchbackend.common.BaseResponse;
import com.th.campusmatchbackend.common.ErrorCode;
import com.th.campusmatchbackend.common.ResultUtils;
import com.th.campusmatchbackend.config.ThirdPartyLoginConfig;
import com.th.campusmatchbackend.exception.BusinessException;
import com.th.campusmatchbackend.model.domain.User;
import com.th.campusmatchbackend.service.UserService;
import com.th.campusmatchbackend.utils.QqHttpClient;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;

import static com.th.campusmatchbackend.contant.UserContant.USER_LOGIN_STATE;

@ApiIgnore
@RestController
@RequestMapping("/loginOptionTwo")
public class ThirdPartyLoginControllerTwo {



    @Resource
    private ThirdPartyLoginConfig thirdPartyLoginConfig;

    @Resource
    private UserService userService;


    /**
     * 请求授权页面
     */
    @GetMapping( "/QQ")
    public BaseResponse<String> qqAuth(HttpSession session)  {
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1：获取Authorization Code
        String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code" +
                "&client_id=" + thirdPartyLoginConfig.getAppId() +
                "&redirect_uri=" + URLEncoder.encode(thirdPartyLoginConfig.getRedirectUrl()) +
                "&state=" + uuid;

        return ResultUtils.success(url);
    }

    /**
     * 授权回调
     */
    @GetMapping( "/loginInfo")
    public void qqCallback(HttpServletRequest request,HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        // 得到Authorization Code
        String code = request.getParameter("code");
        // 我们放在地址中的状态码
        String state = request.getParameter("state");
        // 验证信息
        String uuid = (String) session.getAttribute("state");

        // 验证信息我们发送的状态码
        if (null != uuid) {
            // 状态码不正确，直接返回登录页面
            if (!uuid.equals(state)) {
                throw new BusinessException(ErrorCode.NULL_LOGIN, "请重新登录,uuid不正确");
            }
        }

        // Step2：通过Authorization Code获取Access Token
        String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code" +
                "&client_id=" + thirdPartyLoginConfig.getAppId() +
                "&client_secret=" +thirdPartyLoginConfig.getAppKey() +
                "&code=" + code +
                "&redirect_uri=" + thirdPartyLoginConfig.getRedirectUrl();
        String access_token = QqHttpClient.getAccessToken(url);

        // Step3: 获取回调后的openID
        url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
        String openId = QqHttpClient.getOpenID(url);

        // Step4：获取QQ用户信息
        url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +
                "&oauth_consumer_key=" + thirdPartyLoginConfig.getAppId() +
                "&openid=" + openId;

        // 得到用户信息
        JSONObject jsonObject = QqHttpClient.getUserInfo(url);

        User user = new User();
        if(jsonObject.get("ret").equals(0)){
            // 将 OpenID 字符串转换为 long 类型
            user.setId(Long.parseLong(openId));
            String username = jsonObject.getString("username");
            String gender = jsonObject.getString("gender");
            String avatar = jsonObject.getString("avatar");
            user.setUsername(username);
            user.setAvatarUrl(avatar);
            user.setTags("[]");
            user.setUserIds("[]");
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getUserAccount, user.getUserAccount());
            User one = userService.getOne(userLambdaQueryWrapper);
            if(one != null){
                request.getSession().setAttribute(USER_LOGIN_STATE, user);
                response.sendRedirect("/");
                //return PassWordUtils.redirectTo("/");
            }else{
                if("男".equals(gender)){
                    user.setGender(0);
                }else{
                    user.setGender(1);
                }
                userService.save(user);
                request.getSession().setAttribute(USER_LOGIN_STATE, user);
                response.sendRedirect("/");
                //return PassWordUtils.redirectTo("/");
            }

        }else{
            throw new BusinessException(ErrorCode.NULL_LOGIN, "请重新登录");

        }



    }





}
